<?php

namespace app\taglib;

use think\template\TagLib;

class MyTags extends TagLib
{
    protected $tags = [
        'config' => ['attr' => 'collection,key', 'close' => 1],
        'in' => ['attr' => 'name,value', 'close' => '1'],
        'category' => ['attr' => 'obj,key', 'close' => '1'],
        // attr : 自定义标签的属性, close : 是否闭合标签,下面有说明
    ];

    public function tagConfig($tag, $content)
    {
        $collection = $tag['collection'];
        $key = $tag['key'];

        // 判断空 如果为空 直接返回空字符串
        if (empty($collection) || empty($key)) {
            return '';
        }
        $parseStr = "<?php foreach ({$collection} as \$item): if (\$item['name'] == '{$key}'): ?>";
        // 解析html
        $parseStr .= $content;
        $parseStr .= "<?php break; endif; endforeach; ?>";

        return $parseStr;
    }


    public function tagIn($tag, $content)
    {
        $obj = $tag['obj'];
        $attr = $tag['attr'];
        $value = $tag['value'];
        // 判断$obj如果为空 直接返回false
        if (empty($obj)) {
            return false;
        }

        // 拆分传入的value值为数组
        $values = explode(',', $value);

        $parseStr = "<?php if (isset({$obj}) && in_array({$obj}->{$attr}, [" . implode(',', $values) . "])): ?>";
        $parseStr .= $content;
        $parseStr .= "<?php endif; ?>";

        return $parseStr;
    }


    // 传入对象 和id 获取对应 的obj值
    public function tagCategory($tag, $content)
    {
        $obj = $tag['obj'];
        $key = $tag['key'];
        // 判断$obj如果为空 直接返回false
        if (empty($obj) || empty($key)) {
            return false;
        }

        // 根据array 获取obj中的attr属性的值==id 不需要循环 直接取
        $parseStr = "<?php if (isset({$obj})): ?>";
        $parseStr .= "<?php echo {$obj}->{$key}; ?>";
        $parseStr .= "<?php endif; ?>";

        return $parseStr;
    }
}
